package com.doujiang.Controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.doujiang.domain.Favorite;
import com.doujiang.service.zzqIFavoriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 收藏/想看 控制器
 */
@RestController
@RequestMapping("/favorite")
@CrossOrigin
public class zzqFavoriteController {

    @Autowired
    private zzqIFavoriteService favoriteService;

    /**
     * 获取用户对某部电影的收藏状态
     * 示例请求：
     * GET /favorite?userId=1&movieId=123
     */
    @GetMapping
    public ResponseEntity<Favorite> getFavoriteByUserAndMovie(@RequestParam("userId") Long userId, @RequestParam("movieId") Long movieId) {
        try {
            System.out.println("收到收藏状态查询请求 - 用户ID: " + userId + ", 电影ID: " + movieId);
            
            Favorite favorite = favoriteService.getFavoriteByUserAndMovie(userId, movieId);
            System.out.println("查询到的收藏状态: " + favorite);
            
            if (favorite != null) {
                return ResponseEntity.ok(favorite);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            System.err.println("获取收藏状态时发生错误: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(500).body(null);
        }
    }

    /**
     * 设置或更新收藏状态（1=想看，2=已看）
     * 示例请求：
     * POST /favorite
     * {
     *   "userId": 1,
     *   "movieId": 123,
     *   "type": 1
     * }
     */
    @PostMapping
    public ResponseEntity<Boolean> setFavoriteType(@RequestBody Map<String, Object> payload) {
        Long userId = Long.valueOf(payload.get("userId").toString());
        Long movieId = Long.valueOf(payload.get("movieId").toString());
        Integer type = Integer.valueOf(payload.get("type").toString());

        boolean result = favoriteService.updateFavoriteType(userId, movieId, type);
        return ResponseEntity.ok(result);
    }

    /**
     * 获取用户的片单（想看和已看的电影）
     */
    @GetMapping("/user/{userId}/watchlist")
    public ResponseEntity<List<Favorite>> getUserWatchlist(@PathVariable("userId") Long userId) {
        try {
            System.out.println("获取用户片单 - 用户ID: " + userId);
            List<Favorite> watchlist = favoriteService.getUserWatchlist(userId);
            System.out.println("用户片单数量: " + watchlist.size());
            return ResponseEntity.ok(watchlist);
        } catch (Exception e) {
            System.err.println("获取用户片单时发生错误: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(500).body(null);
        }
    }

    /**
     * 获取用户的所有收藏（包括想看和已看）
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<List<Favorite>> getUserFavorites(@PathVariable("userId") Long userId) {
        try {
            System.out.println("获取用户收藏 - 用户ID: " + userId);
            List<Favorite> favorites = favoriteService.getUserWatchlist(userId);
            System.out.println("用户收藏数量: " + favorites.size());
            return ResponseEntity.ok(favorites);
        } catch (Exception e) {
            System.err.println("获取用户收藏时发生错误: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(500).body(null);
        }
    }

    /**
     * 根据类型获取用户的片单
     */
    @GetMapping("/user/{userId}/watchlist/{type}")
    public ResponseEntity<List<Favorite>> getUserWatchlistByType(
            @PathVariable("userId") Long userId, 
            @PathVariable("type") Integer type) {
        try {
            System.out.println("获取用户片单 - 用户ID: " + userId + ", 类型: " + type);
            List<Favorite> watchlist = favoriteService.getUserWatchlistByType(userId, type);
            System.out.println("用户片单数量: " + watchlist.size());
            return ResponseEntity.ok(watchlist);
        } catch (Exception e) {
            System.err.println("获取用户片单时发生错误: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(500).body(null);
        }
    }

    /**
     * 取消收藏/想看/已看
     */
    @DeleteMapping
    public ResponseEntity<Boolean> cancelFavorite(@RequestParam("userId") Long userId, @RequestParam("movieId") Long movieId) {
        try {
            // 使用软删除，将deleted字段设置为1
            boolean result = favoriteService.lambdaUpdate()
                .eq(Favorite::getUserId, userId)
                .eq(Favorite::getMovieId, movieId)
                .eq(Favorite::getDeleted, 0L) // 只更新未软删除的记录
                .set(Favorite::getDeleted, 1L) // 设置为软删除状态
                .update();
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(false);
        }
    }
}
